let app = getApp()
Page({
    data: {
        ColorMost: app.globalData.ColorMost,
        ColorLess: app.globalData.ColorLess,
        configColor: app.globalData.configColor,
        userId: 0,
        listForAllOil: [],
        carNumber: '',
        selected: [],
        showChooseTitle: false,
        columns: [],
        dateChoose: [
            { index: 0, value: "近三个月" },
            { index: 1, value: "近半年" },
            { index: 2, value: "近一年" },
            { index: 3, value: "全部" },
        ],
        dateChoosed: 1,
        dateColumns: ['近三个月', '近半年', '近一年', '全部'],
        showDataChoose: false,
        infoForAvgOilConsumption: 0,
        infoForAvgOilFee: 0,
        infoForTotal: 0,
        infoForMachineMoney: 0,
        infoForQuantity: 0,
        statusBarHeight: app.globalData.statusBarHeight,
        navBarHeight: app.globalData.navBarHeight,
    },
    onOpenSwipe2(event) {
        // this.selectComponent("#"+ event.currentTarget.dataset.zujianid+"").open("right")
        this.selectComponent("#" + event.currentTarget.dataset.zujianid + "").open("right")
        // this.setData({
        //     selected:event.currentTarget.dataset.zujianid
        // })
    },
    onTap() {
        //这是点击其他区域时，根据id让当前打开的元素关闭
        let instance = this.selectComponent("#" + this.data.selected + "");
        // console.log("#"+ this.data.selected +"")
        if (instance != null) { instance.close(); }
        this.onClose()
    },
    onCloseSwipe(event) {
        const { position, instance } = event.detail;
        event.detail.instance.close();
    },
    onOpenSwipe(event) {
        this.setData({
            selected: event.currentTarget.id
        })
    },
    onConfirmForShowDataChoose(event) {
        const { picker, value, index } = event.detail;
        console.log("当前值：" + value + "当前索引：" + index);
        this.setData({
            dateChoosed: index
        })
        this.showPage(wx.getStorageSync('userInfo').number, index)
        this.onCloseForShowDataChoose()
    },
    openDataChoose() {
        this.setData({
            showDataChoose: true
        });
    },
    onClose() {
        this.setData({
            showChooseTitle: false
        });
    },
    onCloseForShowDataChoose() {
        this.setData({
            showDataChoose: false
        });
    },
    addOil() {
        if (this.selectComponent('#loginPopup').init()) {
            return
        }
        wx.redirectTo({
            url: '/pages/add_oil/add_oil?selectedColumnValue=' + this.data.carNumber
        })
    },
    openChooseTitle() {
        wx.request({
            url: app.globalData.url + '/getAllCarName',
            method: 'GET',
            data: {
                userId: wx.getStorageSync('userInfo').id,
            },
            success: (res) => {
                if (res.data.flag) {
                    // let columnsTemp = this.data.columns
                    let columnsTemp = ['']
                    for (var i = 0; i < res.data.data.length; i++) {
                        // if(res.data.data[i] != this.data.selectedColumnValue){
                        columnsTemp.push(res.data.data[i])
                        // }                
                    }
                    this.setData({
                        columns: columnsTemp,
                        showChooseTitle: true
                    })
                } else {
                    wx.showToast({
                        title: '车牌查询失败，请稍后尝试',
                        icon: 'none'
                    })
                }
            },
            fail: (err) => {
                console.log('车牌查询失败，请稍后尝试!!!', err);
            }
        })
    },
    onChangeTitle(e) {
        if (e.detail.index != 0) {
            this.setData({
                carNumber: e.detail.value
            })
            this.showPage(e.detail.value, this.data.dateChoosed)
        }
    },
    go_edit(e) {
        if (e.currentTarget.dataset.item.userId != wx.getStorageSync('userInfo').id) {
            wx.showToast({
                title: '禁止修改他人账单',
                icon: 'none'
            })
            return
        }
        let oilId = e.currentTarget.dataset.item.id
        let number = this.data.carNumber
        let oilTime = e.currentTarget.dataset.item.oilTime
        let total = e.currentTarget.dataset.item.total
        let oilPrice = e.currentTarget.dataset.item.oilPrice
        let quantity = e.currentTarget.dataset.item.quantity
        let machineMoney = e.currentTarget.dataset.item.machineMoney
        let resultMoney = e.currentTarget.dataset.item.resultMoney
        let isFull = e.currentTarget.dataset.item.isFull
        let isWarn = e.currentTarget.dataset.item.isWarn
        let isRecord = e.currentTarget.dataset.item.isRecord
        wx.navigateTo({
            url: "/pages/add_oil/add_oil?oilId=" + oilId + "&number=" + number + "&oilTime=" + oilTime + "&total=" + total + "&oilPrice=" + oilPrice + "&quantity=" + quantity
                + "&machineMoney=" + machineMoney + "&resultMoney=" + resultMoney + "&isFull=" + isFull + "&isWarn=" + isWarn + "&isRecord=" + isRecord + "&oilTime=" + oilTime
        })
    },
    // 删除单条记录
    delRecord(e) {
        if (e.currentTarget.dataset.userid != wx.getStorageSync('userInfo').id) {
            wx.showToast({
                title: '禁止删除他人记录',
                icon: 'none'
            })
            return
        }
        wx.request({
            url: app.globalData.url + '/delOil',
            method: 'POST',
            data: {
                id: e.currentTarget.dataset.delid,
                optionUserId: wx.getStorageSync('userInfo').id,
                userId: e.currentTarget.dataset.userid
            },
            success: (res) => {
                let re = res.data.flag
                if (re) {
                    this.showPage(wx.getStorageSync('userInfo').number, this.data.dateChoosed)
                } else {
                    wx.showToast({
                        title: '删除失败: ' + res.data.message,
                        icon: 'none'
                    })
                }
            },
            fail: (err) => {
                wx.showToast({
                    title: '删除失败，请稍后尝试',
                    icon: 'none'
                })
            }
        })
    },
    showPage(number, monthIndex) {
        // 获取油耗详细信息
        wx.request({
            url: app.globalData.url + '/getOilInfoByDate',
            method: 'POST',
            header: {
                'content-type': 'application/json'
            },
            data: {
                userId: wx.getStorageSync('userInfo').id,
                number: number,
                monthRangeIndex: monthIndex
            },
            success: (res) => {
                let responseData = res.data
                if (responseData.flag) {
                    try {
                        this.setData({
                            infoForAvgOilConsumption: responseData.data.avgOilConsumption,
                            infoForAvgOilFee: responseData.data.avgOilFee,
                            infoForTotal: responseData.data.total,
                            infoForMachineMoney: responseData.data.machineMoney,
                            infoForQuantity: responseData.data.quantity,
                        })
                    } catch (error) {
                        console.log(error);
                    }
                } else {
                    wx.showToast({
                        title: '查询油耗详情失败，请稍后尝试',
                        icon: 'none'
                    })
                }
                wx.hideLoading()
            },
            fail: (err) => {
                console.log('失败', err);
            }
        })
        // 获取所有油耗记录
        wx.request({
            url: app.globalData.url + '/getOilList',
            method: 'POST',
            header: {
                'content-type': 'application/json'
            },
            data: {
                userId: wx.getStorageSync('userInfo').id,
                number: number,
                monthRangeIndex: monthIndex
            },
            success: (res) => {
                let responseData = res.data
                //   console.log(responseData.data)
                if (responseData.flag) {
                    try {
                        this.setData({
                            listForAllOil: responseData.data
                        })
                    } catch (error) {
                        console.log(error);
                    }
                } else {
                    wx.showToast({
                        title: '查询油耗记录失败，请稍后尝试',
                        icon: 'none'
                    })
                }
                wx.hideLoading()
            },
            fail: (err) => {
                console.log('失败', err);
            }
        })
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        if (this.selectComponent('#loginPopup').init()) {
            return
        }
        if (wx.getStorageSync('ColorMost') !== this.data.ColorMost
            || wx.getStorageSync('ColorLess') !== this.data.ColorLess
            || wx.getStorageSync('configColor') !== this.data.configColor) {
            this.setData({ ColorMost: wx.getStorageSync('ColorMost') });
            this.setData({ ColorLess: wx.getStorageSync('ColorLess') });
            this.setData({ configColor: wx.getStorageSync('configColor') });
        }
        
        if (wx.getStorageSync('userInfo').number) {
            this.setData({
                carNumber: wx.getStorageSync('userInfo').number,
                userId: wx.getStorageSync('userInfo').id,
                columns: []
            })
            this.showPage(wx.getStorageSync('userInfo').number, this.data.dateChoosed)
        } else {

        }
    },
    /**
   * 生命周期函数--监听页面加载
   */
    onLoad(options) {
        wx.hideShareMenu({
            menus: ['shareAppMessage', 'shareTimeline']
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})